home *** CD-ROM | disk | FTP | other *** search
/ Tech Arsenal 1 / Tech Arsenal (Arsenal Computer).ISO / tek-01 / cuj9204.zip / 1004020A < prev    next >
Text File  |  1992-06-02  |  665b  |  29 lines

  1. /* bsearch function */
  2. #include <stdlib.h>
  3.  
  4. void *(bsearch)(const void *key, const void *base,
  5.     size_t nelem, size_t size, _Cmpfun *cmp)
  6.     {    /* search sorted table by binary chop */
  7.     const char *p;
  8.     size_t n;
  9.  
  10.     for (p = (const char *)base, n = nelem; 0 < n; )
  11.         {    /* check midpoint of whatever is left */
  12.         const size_t pivot = n > 1;
  13.         const char *const q = p + size * pivot;
  14.         const int val = (*cmp)(key, q);
  15.  
  16.         if (val  0)
  17.             n = pivot;    /* search below pivot */
  18.         else if (val == 0)
  19.             return ((void *)q);    /* found */
  20.         else
  21.             {    /* search above pivot */
  22.             p = q + size;
  23.             n -= pivot + 1;
  24.             }
  25.         }
  26.     return (NULL);    /* no match */
  27.     }
  28.  
  29.